/**
 * @title: CustomAuthorizationInterceptor
 * @projectName mscloud
 * @Description TODO
 * @Author
 * @Date 2021/8/25 11:29
 */
package com.sugon.magicapi.interceptor;


import com.sugon.magicapi.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.ssssssss.magicapi.exception.MagicLoginException;
import org.ssssssss.magicapi.interceptor.Authorization;
import org.ssssssss.magicapi.interceptor.AuthorizationInterceptor;
import org.ssssssss.magicapi.interceptor.MagicUser;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义用户名密码登录
 */
//@Component  //注入到Spring容器中
public class CustomAuthorizationInterceptor implements AuthorizationInterceptor {

    @Autowired
    JWTUtils jwtUtils;
    /**
     * 配置是否需要登录
     */
    @Override
    public boolean requireLogin() {
        return true;
    }

    /**
     * 根据Token获取User
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {
        if (!jwtUtils.getUserNameFromToken(token).equals("nopass")) {
            return new MagicUser("",jwtUtils.getUserNameFromToken(token),token);   // 从token中获取MagicUser对象
        }
        throw new MagicLoginException("token无效");
    }

    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        // 根据实际情况进行修改。。
        if("admin".equals(username) && password.equals("2605339")){
            // 登录成功后 构造MagicUser对象。
            return new MagicUser("1","admin",jwtUtils.generateToken("admin"));
        }
        throw new MagicLoginException("用户名或密码不正确");
    }

    /**
     * 验证是否有权限访问功能
     */
    @Override
    public boolean allowVisit(MagicUser magicUser, HttpServletRequest request, Authorization authorization) {
        // Authorization.SAVE   执行保存接口、函数、数据源
        // Authorization.VIEW   查看接口、函数、数据源
        // Authorization.DELETE 删除接口、函数、数据源
        // Authorization.DOWNLOAD   导出接口、函数
        // Authorization.UPLOAD   上传
        // Authorization.PUSH 推送

        // 不允许删除
        return authorization != Authorization.DELETE;
    }

}